package com.yex.service.modify;

import com.yex.common.exception.RRException;
import com.yex.dao.WalletDao;
import com.yex.entity.UserEntity;
import com.yex.entity.WalletEntity;
import com.yex.util.CommonModifyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service(value = "MyWalletService")
@Transactional
public class WalletService extends BaseService<WalletDao, WalletEntity> {

    public WalletEntity getLoginUserWallet() {
        UserEntity userEntity = validateLoginUser(CommonModifyUtil.getRequest());
        return baseMapper.selectByUserId(userEntity.getId());
    }

    public void frozen(Integer userId, BigDecimal frozen) {
        frozen = frozen.setScale(2, BigDecimal.ROUND_HALF_UP);
        WalletEntity walletEntity = baseMapper.selectByUserId(userId);
        if (walletEntity.getTotal().compareTo(frozen) < 0) throw new RRException("用户余额不足");
        WalletEntity walletEntity1 = new WalletEntity();
        walletEntity1.setFrozen(frozen);
        walletEntity1.setId(walletEntity.getId());
        Integer count = baseMapper.updateFrozen(walletEntity1);
        if (count > 1) throw new RRException("更新余额失败");
    }

    public void unfrozen(Integer userId, BigDecimal frozen) {
        frozen = frozen.setScale(2, BigDecimal.ROUND_HALF_UP);
        WalletEntity walletEntity = baseMapper.selectByUserId(userId);
        if (walletEntity.getFrozen().compareTo(frozen) < 0) frozen = walletEntity.getFrozen();
        WalletEntity walletEntity1 = new WalletEntity();
        walletEntity1.setFrozen(frozen);
        walletEntity1.setId(walletEntity.getId());
        Integer count = baseMapper.updateUnFrozen(walletEntity1);
        if (count > 1) throw new RRException("更新余额失败");
    }

    public void transferUser(Integer userId, Integer transferId, BigDecimal frozen) {
        //  减少user的冻结数量
        WalletEntity walletEntity = baseMapper.selectByUserId(userId);
        if (walletEntity.getFrozen().compareTo(frozen) < 0) frozen = walletEntity.getFrozen();
        walletEntity.setFrozen(frozen);
        baseMapper.updateReduceFrozen(walletEntity);

        walletEntity = baseMapper.selectByUserId(transferId);
        walletEntity.setTotal(frozen);
        baseMapper.updateAdd(walletEntity);
    }

    public void updateAdd(Integer userId, BigDecimal price) {
        WalletEntity walletEntity = baseMapper.selectByUserId(userId);
        if (walletEntity == null) throw new RRException("转账失败");
        walletEntity.setTotal(price);
        Integer count = baseMapper.updateAdd(walletEntity);
        if (count > 1) throw new RRException("转账失败");
    }

    public WalletEntity selectByUserId(Integer userId) {
        return baseMapper.selectByUserId(userId);
    }

}
